package com.qd.qx.ui.main.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qd.common.base.BaseActivity;
import com.qd.common.baserx.RxBus;
import com.qd.common.commonutils.LogUtils;
import com.qd.qx.R;
import com.qd.qx.api.MyXMPPTCPConnection;
import com.qd.qx.app.AppConstants;
import com.qd.qx.bean.MTabEntity;
import com.qd.qx.bean.TabViewEntity;
import com.qd.qx.ui.module1.MessageFragment;
import com.qd.qx.ui.module2.AddressBookFragment;
import com.qd.qx.ui.module3.WorkBenchFragment;
import com.qd.qx.ui.module4.MyFragment;
import com.qd.qx.widget.BadgeView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import rx.functions.Action1;

/**
 * des:主界面
 */
public class MainActivity extends BaseActivity {
    @BindView(R.id.ivOne)
    ImageView ivOne;
    @BindView(R.id.tvOne)
    TextView tvOne;
    @BindView(R.id.llOne)
    LinearLayout llOne;
    @BindView(R.id.ivTwo)
    ImageView ivTwo;
    @BindView(R.id.tvTwo)
    TextView tvTwo;
    @BindView(R.id.llTwo)
    LinearLayout llTwo;
    @BindView(R.id.ivThree)
    ImageView ivThree;
    @BindView(R.id.tvThree)
    TextView tvThree;
    @BindView(R.id.llThree)
    LinearLayout llThree;
    @BindView(R.id.ivFour)
    ImageView ivFour;
    @BindView(R.id.tvFour)
    TextView tvFour;
    @BindView(R.id.llFour)
    LinearLayout llFour;
    @BindView(R.id.ll_tablayout)
    LinearLayout llTablayout;
    @BindView(R.id.ll_messageBadge)
    LinearLayout llMessageBadge;
    private String[] mTitles = {"消息", "通讯录", "圈子", "我的"};
    private int[] mIconUnselectIds = {
            R.drawable.xiao_xi_nor, R.drawable.tong_xun_lu, R.drawable.gong_zuo_tai, R.drawable.wo_de};
    private int[] mIconSelectIds = {
            R.drawable.xiao_xi_xz, R.drawable.tong_xun_lu_xz, R.drawable.gong_zuo_tai_xz, R.drawable.wo_de_xz};
    private ArrayList<MTabEntity> mTabEntityArrayList = new ArrayList<>();
    private ArrayList<TabViewEntity> tabViewEntityArrayList = new ArrayList<>();
    private MessageFragment messageFragment;
    private AddressBookFragment addressBookFragment;
    private WorkBenchFragment workBenchFragment;
    private MyFragment myFragment;
    private int currentTabPosition = 0;//当前页面下标
    private BadgeView badgeView;

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.fade_in,
                com.qd.common.R.anim.fade_out);
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_main;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        //初始化菜单
        badgeView = new BadgeView(this);
        initTab();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化frament
        initFragment(savedInstanceState);
        //初始化未读消息监听
        refreshMessageUnreadCountShow();
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if ((intent.getFlags() | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) > 0) {
            if (android.os.Build.VERSION.SDK_INT >= 19 && !isTaskRoot()) {
                ActivityManager tasksManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                tasksManager.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_NO_USER_ACTION);
            }
        }
    }
    /**
     * 初始化tab
     */
    private void initTab() {
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntityArrayList.add(new MTabEntity(mIconSelectIds[i], mIconUnselectIds[i]));
        }
        tabViewEntityArrayList.add(new TabViewEntity(tvOne, ivOne));
        tabViewEntityArrayList.add(new TabViewEntity(tvTwo, ivTwo));
        tabViewEntityArrayList.add(new TabViewEntity(tvThree, ivThree));
        tabViewEntityArrayList.add(new TabViewEntity(tvFour, ivFour));
        badgeView.setTargetView(llMessageBadge);

    }

    /**
     * 设置底部消息 未读消息展示
     */
    private void refreshMessageUnreadCountShow() {
        RxBus.getInstance().register(AppConstants.REFRESH_ALLUNREADCOUNT).subscribe(new Action1() {
            @Override
            public void call(Object o) {
                final int count = (int) o;
                if (null != badgeView) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            badgeView.setBadgeCount(count);
                        }
                    });
                }
            }
        });


    }

    /**
     * 初始化碎片
     */
    private void initFragment(Bundle savedInstanceState) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (savedInstanceState != null) {
            messageFragment = (MessageFragment) getSupportFragmentManager().findFragmentByTag("messageFragment");
            addressBookFragment = (AddressBookFragment) getSupportFragmentManager().findFragmentByTag("addressBookFragment");
            workBenchFragment = (WorkBenchFragment) getSupportFragmentManager().findFragmentByTag("workBenchFragment");
            myFragment = (MyFragment) getSupportFragmentManager().findFragmentByTag("myFragment");
            currentTabPosition = savedInstanceState.getInt(AppConstants.HOME_CURRENT_TAB_POSITION);
        } else {

            messageFragment = new MessageFragment();
            addressBookFragment = new AddressBookFragment();
            workBenchFragment = new WorkBenchFragment();
            myFragment = new MyFragment();

            transaction.add(R.id.fl_body, messageFragment, "messageFragment");
            transaction.add(R.id.fl_body, addressBookFragment, "addressBookFragment");
            transaction.add(R.id.fl_body, workBenchFragment, "workBenchFragment");
            transaction.add(R.id.fl_body, myFragment, "myFragment");
        }
        transaction.commit();
        SwitchTo(currentTabPosition);
        // new QBadgeView(this).bindTarget(llMessageBadge).setBadgeNumber(5).setBadgeTextSize(8,true).setShowShadow(false);
        badgeView.setBadgeMargin(0, 2, 2, 0);
    }

    /**
     * 切换
     */
    private void SwitchTo(int position) {
        LogUtils.logd("主页菜单position" + position);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        changgeShow(position);
        switch (position) {
            case 0:
                transaction.hide(addressBookFragment);
                transaction.hide(workBenchFragment);
                transaction.hide(myFragment);
                transaction.show(messageFragment);
                transaction.commitAllowingStateLoss();
                break;
            case 1:
                transaction.hide(messageFragment);
                transaction.hide(workBenchFragment);
                transaction.hide(myFragment);
                transaction.show(addressBookFragment);
                transaction.commitAllowingStateLoss();
                break;
            case 2:
                transaction.hide(messageFragment);
                transaction.hide(addressBookFragment);
                transaction.hide(myFragment);
                transaction.show(workBenchFragment);
                transaction.commitAllowingStateLoss();
                break;
            case 3:
                transaction.hide(messageFragment);
                transaction.hide(addressBookFragment);
                transaction.hide(workBenchFragment);
                transaction.show(myFragment);
                transaction.commitAllowingStateLoss();

                break;
            default:
                break;
        }

    }


    private void changgeShow(int index) {
        for (int i = 0; i < mTabEntityArrayList.size(); i++) {
            if (index == i) {
                tabViewEntityArrayList.get(i).getImageView().setBackgroundResource(mTabEntityArrayList.get(i).getSelectImg());
                tabViewEntityArrayList.get(i).getTextView().setTextColor(Color.parseColor("#0079ff"));
            } else {
                tabViewEntityArrayList.get(i).getImageView().setBackgroundResource(mTabEntityArrayList.get(i).getUnSelectImg());
                tabViewEntityArrayList.get(i).getTextView().setTextColor(Color.parseColor("#8a8a8a"));
            }
        }
    }

    /**
     * 监听全屏视频时返回键
     */
    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //奔溃前保存位置
        if (null != llTablayout) {
            outState.putInt(AppConstants.HOME_CURRENT_TAB_POSITION, currentTabPosition);
        }
    }

    @Override
    protected void onResume() {
        int count = MyXMPPTCPConnection.getInstance().refreshAllUnreadCount();
        badgeView.setBadgeCount(count);
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @OnClick({R.id.llOne, R.id.llTwo, R.id.llThree, R.id.llFour})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.llOne:
                SwitchTo(0);
                break;
            case R.id.llTwo:
                SwitchTo(1);
                break;
            case R.id.llThree:
                SwitchTo(2);
                break;
            case R.id.llFour:
                SwitchTo(3);
                break;
        }
    }
}
